import sys
import json
import urllib.parse
import urllib.request
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLineEdit, QPushButton, QTableWidget, QTableWidgetItem, QHeaderView,
    QLabel, QMessageBox
)
from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QFont, QDesktopServices, QColor, QPalette


class ResourceSearchApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("网盘资源搜索工具 🌌")
        # 设置窗口大小
        self.setGeometry(300, 300, 900, 700)

        # --- 深色模式配色方案 ---
        # 设置调色板，使用深色背景和高对比度色彩
        palette = self.palette()
        # 主背景色 (深灰色/炭黑色)
        palette.setColor(QPalette.Window, QColor("#282c34")) 
        # 窗口文字颜色 (亮灰色)
        palette.setColor(QPalette.WindowText, QColor("#ecf0f1")) 
        # 控件底色 (如输入框和表格背景)
        palette.setColor(QPalette.Base, QColor("#3c4048")) 
        # 文本颜色
        palette.setColor(QPalette.Text, QColor("#ecf0f1")) 
        # 按钮/高亮色 (鲜艳的蓝色)
        palette.setColor(QPalette.Button, QColor("#61afef")) 
        palette.setColor(QPalette.ButtonText, QColor("#282c34")) # 按钮文字颜色
        palette.setColor(QPalette.Highlight, QColor("#61afef")) # 选中高亮颜色
        palette.setColor(QPalette.HighlightedText, QColor("#282c34")) # 选中文字颜色
        self.setPalette(palette)

        # 设置主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout(main_widget)
        # 增加边距和间距
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)

        # 设置字体
        font = QFont("Segoe UI", 10)
        self.setFont(font)

        # 搜索区域
        search_layout = QHBoxLayout()
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("在此输入搜索关键词...")
        self.search_input.returnPressed.connect(self.search_resources)
        self.search_input.setFixedHeight(40) # 增加输入框高度
        # 输入框样式：圆角、深色背景、亮色文字
        self.search_input.setStyleSheet("""
            QLineEdit {
                padding: 10px;
                border: 1px solid #4e535e;
                border-radius: 8px;
                font-size: 14px;
                color: #ecf0f1;
                background-color: #3c4048;
            }
            QLineEdit:focus {
                border: 1px solid #61afef; /* 聚焦时边框高亮 */
                background-color: #3c4048;
            }
        """)
        search_layout.addWidget(self.search_input)

        self.search_btn = QPushButton("搜索")
        self.search_btn.clicked.connect(self.search_resources)
        self.search_btn.setFixedHeight(40)
        # 按钮样式：醒目蓝色背景、深色文字、圆角、加粗
        self.search_btn.setStyleSheet("""
            QPushButton {
                background-color: #61afef;
                color: #282c34;
                border: none;
                border-radius: 8px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #559edc;
            }
            QPushButton:pressed {
                background-color: #4a8bcc;
            }
        """)
        search_layout.addWidget(self.search_btn)
        main_layout.addLayout(search_layout)

        # 结果表格
        self.result_table = QTableWidget()
        # 只需要四列：名称、类型、链接、提取码
        self.result_table.setColumnCount(4)
        self.result_table.setHorizontalHeaderLabels(["资源名称", "网盘类型", "分享链接", "提取码"])
        # 调整列宽
        self.result_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.result_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.result_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.result_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        self.result_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.result_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.result_table.doubleClicked.connect(self.open_link)

        # 表格样式：深色背景、亮色文字、蓝色高亮
        self.result_table.setStyleSheet("""
            QTableWidget {
                border: 1px solid #4e535e;
                border-radius: 8px;
                font-size: 13px;
                background-color: #3c4048; /* 表格底色 */
                gridline-color: #4e535e;
                color: #ecf0f1;
                selection-background-color: #61afef; /* 选中行颜色 */
                selection-color: #282c34;
            }
            QHeaderView::section {
                background-color: #4e535e; /* 表头背景 */
                color: #ecf0f1;
                padding: 10px;
                border-bottom: 2px solid #61afef; /* 表头底部蓝色装饰线 */
                font-weight: bold;
            }
            QTableWidget::item {
                padding: 6px;
            }
        """)

        main_layout.addWidget(self.result_table)

        # 状态标签
        self.status_label = QLabel("就绪")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setStyleSheet("color: #99aab5; font-size: 12px;")
        main_layout.addWidget(self.status_label)

    def search_resources(self):
        keyword = self.search_input.text().strip()
        if not keyword:
            QMessageBox.warning(self, "输入错误", "请输入搜索关键词 📝")
            return

        self.status_label.setText("搜索中... ⏳")
        QApplication.processEvents()  # 确保UI更新

        try:
            # 构造API请求URL
            encoded_keyword = urllib.parse.quote(keyword)
            api_url = f"https://pansou.252035.xyz/api/search?kw={encoded_keyword}&refresh=false&res=merge&src=all&plugins="

            # 发送HTTP请求
            with urllib.request.urlopen(api_url) as response:
                data = json.loads(response.read().decode('utf-8'))

                # 检查API响应状态
                if data.get('code') != 0:
                    self.status_label.setText(f"API错误: {data.get('message', '未知错误')} ❌")
                    return

                # 处理返回的数据
                self.process_results(data.get('data', {}))
                if self.result_table.rowCount() > 0:
                    self.status_label.setText(f"找到 {self.result_table.rowCount()} 条结果 🎉")
                else:
                    self.status_label.setText("没有找到相关结果 🤷‍♀️")

        except Exception as e:
            self.status_label.setText(f"发生错误: {str(e)} ❗")
            self.result_table.setRowCount(0)

    def process_results(self, data):
        # 清空表格
        self.result_table.setRowCount(0)

        if not data or 'merged_by_type' not in data:
            return

        # 遍历所有网盘类型（确保处理 merged_by_type 下的所有资源）
        for pan_type, resources in data['merged_by_type'].items():
            if not resources:
                continue

            # 处理每个资源
            for resource in resources:
                row = self.result_table.rowCount()
                self.result_table.insertRow(row)

                # 资源名称 (列 0)
                note = resource.get('note', '未知名称')
                self.result_table.setItem(row, 0, QTableWidgetItem(note))

                # 网盘类型 (列 1)
                self.result_table.setItem(row, 1, QTableWidgetItem(pan_type))

                # 分享链接 (列 2)
                url = resource.get('url', '')
                if url and not url.startswith('http'):
                    url = 'https://' + url # 确保链接有协议头
                link_item = QTableWidgetItem(url)
                link_item.setToolTip(url) # 鼠标悬停显示完整链接
                self.result_table.setItem(row, 2, link_item)

                # 提取码 (列 3)
                password = resource.get('password', '无')
                self.result_table.setItem(row, 3, QTableWidgetItem(password))

    def open_link(self, index):
        # 仅双击“分享链接”列 (索引为 2) 时打开链接
        if index.column() == 2:
            url = self.result_table.item(index.row(), 2).text()
            if url:
                QDesktopServices.openUrl(QUrl(url))


if __name__ == "__main__":
    # 启用高清DPI缩放，确保界面在高分辨率屏幕上正常显示
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
    
    app = QApplication(sys.argv)
    window = ResourceSearchApp()
    window.show()
    sys.exit(app.exec())